package util;

import entity.TransResponse;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

public class TranslateUtil {
	// 有道接口
	// public static final String URL = "http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=";
	public static final String URL = "https://aidemo.youdao.com//trans_html";
	/** 不同内容的间隔符，这里使用了html5不存在的标签 */
	public static final String SEPARATOR = "<sep />";
	/** 一次请求最大字符数 */
	public static final int MAX_LEN = 5000;

	public static String translate(String s) {
		if (s.trim().equals("")) return " ";
		try {
			String jsonData = Jsoup.connect(URL)
					.ignoreContentType(true)
					.ignoreHttpErrors(true)
					.data("q", s)
					.data("from", "en")
					.data("to", "zh-CHS")
					.method(Connection.Method.POST)
					.execute()
					.body();
			TransResponse transResponse = TransResponse.parse(jsonData);
			if (transResponse.getErrorCode() != null && transResponse.getErrorCode() == 411) {
				// 请求频率过快
				TimeUnit.SECONDS.sleep(3);
				return translate(s);
			}

			return transResponse.getData().getTranslation();
		} catch (IOException | InterruptedException e) {

			throw new RuntimeException(e);
		}
	}

	/**
	 * 批量翻译，免费试用的接口每分钟调用次数有限，只好合并之后一块翻译请求
	 */
	public static List<String> translate(List<String> list) {
		LinkedList<StringBuilder> l = new LinkedList<>();
		l.add(new StringBuilder());

		list.forEach(s -> {
			if (s.length() > MAX_LEN) {
				// 分割
				Arrays.stream(s.split("\\. "))//根据点空格来分
						.flatMap(s1 -> {
							if (s1.length() <= MAX_LEN) return Stream.of(s1);
							return Arrays.stream(s1.split(","));
						})
						.forEach(s1 -> {
							final StringBuilder b = l.getLast();
							if (b.length() + s1.length() + 1 > MAX_LEN) {
								// 作为新的请求
								StringBuilder newB = new StringBuilder();
								newB.append(s1);
								l.add(newB);
							} else {
								// 接在后面
								if (b.length() != 0) b.append("。");
								b.append(s1);
							}
						});
			} else {
				final StringBuilder b = l.getLast();
				if (b.length() + SEPARATOR.length() + s.length() > MAX_LEN) {
					// 作为新的请求
					StringBuilder newB = new StringBuilder();
					newB.append(s);
					l.add(newB);
				} else {
					// 接在后面
					if (b.length() != 0) b.append(SEPARATOR);
					b.append(s);
				}
			}
		});

		return l.stream().flatMap(stringBuilder -> Stream.of(translate(stringBuilder.toString()).split(SEPARATOR))).toList();
	}
}
